﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace PreContractWeb.Task
{
    public partial class ImportPreContract : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            this.tabDocument.Attributes.Add("onSelectedIndexChange", "ResizeDivForScroll('divGridThree','');ResizeDivForScroll('divGrid','');ResizeDivForScroll('divGridTwo');");
            if (!Page.IsPostBack)
            {
                this.txtStartDate.Text = System.DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                this.txtEndDate.Text = System.DateTime.Now.ToString("yyyy-MM-dd");

                this.UploadData = null;
                this.ValidateData = null;
                this.UpdatedData = null;

                
            }
            
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            if (this.NewData == null)
                return;
            for (int i = 0; i < this.gvNew.Rows.Count; i++)
            {
                CheckBox ck = this.gvNew.Rows[i].FindControl("chkNewSelect") as CheckBox;

                if (ck.Checked)
                {
                    this.UpdatePreContract(i, true);
                }
            }

            this.BindGridView();

            ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "Resize", "<script>ResizeDivForScroll('divGridThree','');ResizeDivForScroll('divGrid');ResizeDivForScroll('divGridTwo');</script>", false);

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (this.ValidateData == null)
                return;
            for (int i = 0; i < this.gvMain.Rows.Count; i++)
            {
                CheckBox ck = this.gvMain.Rows[i].FindControl("chkSelect") as CheckBox;

                if (ck.Checked)
                {
                    this.UpdatePreContract(i,false);
                }
            }

            this.BindGridView();

            ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "Resize", "<script>ResizeDivForScroll('divGridThree','');ResizeDivForScroll('divGrid');ResizeDivForScroll('divGridTwo');</script>", false);

        }
        protected void btnImport_Click(object sender, EventArgs e)
        {

            //BEGDC.PreContract.BLL.IPreContractInfo contractservice =(BEGDC.PreContract.BLL.IPreContractInfo)  BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_PreContractInfo_Service];
            //System.Data.DataTable dt = contractservice.GetPreContractInfo_DataTable(string.Empty);

            //if (dt.Rows.Count == 0)
            //{
            //    DataRow row = dt.NewRow();

            //    foreach (DataColumn col in dt.Columns)
            //    {
            //        col.AllowDBNull = true;
            //        row[col] = DBNull.Value;
            //    }
            //    dt.Rows.Add(row);

            //}

            //gvMain.DataSource = dt;
            //gvMain.DataBind();

            this.GetData();

            ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "Resize", "<script>ResizeDivForScroll('divGridThree','');ResizeDivForScroll('divGrid','');ResizeDivForScroll('divGridTwo');</script>", false);
        }

        protected System.Data.DataTable UploadData
        {
            get
            {
                if (Session["UploadData"] == null) return null;
                return Session["UploadData"] as System.Data.DataTable;
            }
            set
            {
                Session["UploadData"] = value;
            }
        }

        protected System.Data.DataTable UpdatedData
        {
            get
            {
                if (Session["UpdatedData"] == null) return null;
                return Session["UpdatedData"] as System.Data.DataTable;
            }
            set
            {
                Session["UpdatedData"] = value;
            }
        }

        protected System.Data.DataTable NewData
        {
            get
            {
                if (Session["NewData"] == null) return null;
                return Session["NewData"] as System.Data.DataTable;
            }
            set
            {
                Session["NewData"] = value;
            }
        }

        protected System.Data.DataTable ValidateData
        {
            get
            {
                if (Session["ValidateData"] == null) return null;
                return Session["ValidateData"] as System.Data.DataTable;
            }
            set
            {
                Session["ValidateData"] = value;
            }
        }

        private void GetData()
        {
            try
            {
                string url = System.Configuration.ConfigurationManager.AppSettings["Lotus_URL_PreContractInfo"];

                string start_date = this.txtStartDate.Text;
                string end_date = this.txtEndDate.Text;
                string strRet = string.Empty;

                url = string.Format(url, start_date, end_date);

                bool bRet = LotusDataRequester.GetDataByAuthentication(url, out strRet);

                if (!bRet)
                {
                    ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1,this.GetType(), "", "<script>alert('调用 Lotus 服务错误, 请确认服务地址正确.')</script>",false);

                    BaseFunction.CreateLog(BEGDC.PreContract.BLL.OperationLog.OperationType.ImportPreContract, strRet, User.Identity.Name);

                }

                DataSet ds = new DataSet();

                System.IO.StringReader reader = new System.IO.StringReader(strRet);

                ds.ReadXml(reader);

                DataTable dtUpload = ds.Tables["record"];

                System.Data.DataTable dtUpdated = new DataTable();
                System.Data.DataTable dtDiff = new DataTable();
                System.Data.DataTable dtValidate = new DataTable();
                System.Data.DataTable dtNew = new DataTable();

                string strMessage = string.Empty;

                BEGDC.PreContract.BLL.IPreContractInfo precontractServuce = (BEGDC.PreContract.BLL.IPreContractInfo)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_PreContractInfo_Service];

                precontractServuce.ImportPreContract(dtUpload, out dtNew, out dtDiff, out dtUpdated,out strMessage);

                if (strMessage != string.Empty)
                {
                    ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "", strMessage,false);
                    //ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1,this.GetType(), "", strMessage);
                    return;
                }

                this.UpdatedData = dtUpdated;

                this.ValidateData = dtDiff;

                this.UploadData = dtUpload;

                this.NewData = dtNew;

                this.BindGridView();

                BaseFunction.CreateLog(BEGDC.PreContract.BLL.OperationLog.OperationType.ImportPreContract, BEGDC.PreContract.BLL.OperationLog.OperationType.ImportPreContract.ToString(), User.Identity.Name);
            }
            catch (Exception ex)
            {

                ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1,this.GetType(), "", "<script>alert('" + ex.Message.Replace("'","\\'") + "')</script>",false);
            }
        }

        protected void BindGridView()
        {
            this.gv_Updated.DataSource = this.UpdatedData;
            this.gv_Updated.DataBind();

            this.totalSpan_Updated.InnerText = this.UpdatedData.Rows.Count.ToString();

            this.gvMain.DataSource = this.ValidateData;
            this.gvMain.DataBind();

            this.totalSpan.InnerText = this.ValidateData.Rows.Count.ToString();

            this.gvNew.DataSource = this.NewData;
            this.gvNew.DataBind();
            this.NewSpan.InnerText = this.NewData.Rows.Count.ToString();
        }

        protected void gvMain_RowDataBound(object sender, GridViewRowEventArgs e)
            {
            if (e.Row.RowIndex >= 0)
            {

                LinkButton lnkARID = (LinkButton)e.Row.FindControl("lnkPreContractNo");
                lnkARID.Attributes.Add("onclick", "javascript:ShowPage('" + e.Row.Cells[0].Text.Trim() + "'); return false;");
                lnkARID.Text = e.Row.Cells[1].Text.Trim();

                string precontractNo = e.Row.Cells[1].Text.Trim();
                string bd = e.Row.Cells[36].Text.Trim();

                System.Data.DataTable dt = this.UploadData;

                System.Data.DataRow[] drs = dt.Select(string.Format("ContractNumber='{0}' And BD='{1}'", precontractNo, bd));
                if (drs == null || drs.Length == 0)
                    return;

                System.Data.DataRow dr = drs[0];

                string PromisedDate_Old = e.Row.Cells[2].Text.Trim();
                string PromisedDate_New = dr["EstimatedDate"].ToString().Trim();
                
                    
                RadioButton rdoPromisedDate_Old = (RadioButton)e.Row.FindControl("PromisedDate_Old");
                RadioButton rdoPromisedDate_New = (RadioButton)e.Row.FindControl("PromisedDate_New");
                rdoPromisedDate_Old.Text = PromisedDate_Old;

                if (PromisedDate_New != string.Empty)
                {
                    if (Convert.ToDateTime(PromisedDate_Old) == Convert.ToDateTime(PromisedDate_New))
                    {
                        rdoPromisedDate_New.Style.Add("visibility", "hidden");
                    }
                    else
                    {
                        rdoPromisedDate_New.Text = PromisedDate_New;
                        rdoPromisedDate_New.Checked = false;
                        rdoPromisedDate_Old.Checked = true;
                    }
                }
                else
                {
                    rdoPromisedDate_New.Text = PromisedDate_New;
                    rdoPromisedDate_New.Checked = false;
                    rdoPromisedDate_Old.Checked = true;
                }

                string CEWPromised_Old = Convert.ToString(Math.Round(Convert.ToDouble(e.Row.Cells[3].Text.Trim()), 2));
                string CEWPromised_New = dr["Price"].ToString().Trim();
                if (CEWPromised_New == string.Empty)
                    CEWPromised_New = "0";
                RadioButton rdoCEWPromised_Old = (RadioButton)e.Row.FindControl("CEWPromised_Old");
                RadioButton rdoCEWPromised_New = (RadioButton)e.Row.FindControl("CEWPromised_New");
                rdoCEWPromised_Old.Text = CEWPromised_Old;
                if (Convert.ToDecimal(CEWPromised_Old) == Convert.ToDecimal(CEWPromised_New))
                {
                    rdoCEWPromised_New.Style.Add("visibility", "hidden");
                }
                else
                {
                    rdoCEWPromised_New.Text = CEWPromised_New;
                    rdoCEWPromised_New.Checked = false;
                    rdoCEWPromised_Old.Checked = true;
                }

                string OrionNo_Old = e.Row.Cells[4].Text.Trim();
                string OrionNo_New = dr["OrionNumber"].ToString().Trim();
                RadioButton rdoOrionNo_Old = (RadioButton)e.Row.FindControl("OrionNo_Old");
                RadioButton rdoOrionNo_New = (RadioButton)e.Row.FindControl("OrionNo_New");
                rdoOrionNo_Old.Text = OrionNo_Old;
                if (OrionNo_Old == OrionNo_New)
                {
                    rdoOrionNo_New.Style.Add("visibility", "hidden");
                }
                else
                {
                    rdoOrionNo_New.Text = OrionNo_New;
                    rdoOrionNo_New.Checked = false;
                    rdoOrionNo_Old.Checked = true;
                }


                string ACRNo_Old = e.Row.Cells[5].Text.Replace("&nbsp;","").Trim();
                string ACRNo_New = dr["EndACR"].ToString().Trim();
                RadioButton rdoACRNo_Old = (RadioButton)e.Row.FindControl("ACRNo_Old");
                RadioButton rdoACRNo_New = (RadioButton)e.Row.FindControl("ACRNo_New");
                rdoACRNo_Old.Text = ACRNo_Old;
                if (ACRNo_Old == ACRNo_New)
                {
                    rdoACRNo_New.Style.Add("visibility", "hidden");
                }
                else
                {
                    rdoACRNo_New.Text = ACRNo_New;
                    rdoACRNo_New.Checked = false;
                    rdoACRNo_Old.Checked = true;
                }

                string CustomerName_Old = e.Row.Cells[6].Text.Trim();
                string CustomerName_New = dr["EndCustomer"].ToString().Trim();
                RadioButton rdoCustomerName_Old = (RadioButton)e.Row.FindControl("CustomerName_Old");
                RadioButton rdoCustomerName_New = (RadioButton)e.Row.FindControl("CustomerName_New");
                rdoCustomerName_Old.Text = CustomerName_Old;
                if (CustomerName_Old == CustomerName_New)
                {
                    rdoCustomerName_New.Style.Add("visibility", "hidden");
                }
                else
                {
                    rdoCustomerName_New.Text = CustomerName_New;
                    rdoCustomerName_New.Checked = false;
                    rdoCustomerName_Old.Checked = true;
                }
            }

        }

        protected void gvMain_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Upd")
            {
                int iIndex = Convert.ToInt16(e.CommandArgument);

                UpdatePreContract(iIndex, false);

                this.BindGridView();

                ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "Resize", "<script>ResizeDivForScroll('divGridThree','');ResizeDivForScroll('divGrid','');ResizeDivForScroll('divGridTwo');</script>", false);

                this.DocDetail.Focus();
            }
        }

        protected void gvUpdated_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowIndex >= 0)
            {

                LinkButton lnkARID = (LinkButton)e.Row.FindControl("lnkPreContractNo");
                lnkARID.Attributes.Add("onclick", "javascript:ShowPage('" + e.Row.Cells[0].Text.Trim() + "');return false;");
                lnkARID.Text = e.Row.Cells[1].Text.Trim();

            }

        }

        private void UpdatePreContract(int iIndex, bool isNew)
        {
            string precontractId = string.Empty;
            string precontractNo = string.Empty;
            string bd = string.Empty;

            BEGDC.PreContract.BLL.IPreContractInfo precontractServuce = (BEGDC.PreContract.BLL.IPreContractInfo)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_PreContractInfo_Service];
            string strMessage = string.Empty;

            if (isNew)
            {
                precontractId = string.Empty;
                precontractNo = gvNew.Rows[iIndex].Cells[1].Text.Trim();
                bd = gvNew.Rows[iIndex].Cells[28].Text.Trim();
            }
            else
            {
                precontractId = gvMain.Rows[iIndex].Cells[0].Text.Trim();
                precontractNo = gvMain.Rows[iIndex].Cells[1].Text.Trim();
                bd = gvMain.Rows[iIndex].Cells[36].Text.Trim();
            }


            System.Data.DataRow[] drs = this.UploadData.Select(string.Format("ContractNumber='{0}' And BD='{1}'", precontractNo,bd));
            if (drs == null || drs.Length == 0)
                return;

            System.Data.DataRow dr = drs[0];

            System.Data.DataRow dr_V = this.ValidateData.NewRow();

            if (!isNew)
            {
                //Alan 2008/11/11
                System.Data.DataRow[] drs_V = this.ValidateData.Select(string.Format("PreContractId='{0}'", precontractId));
                if (drs_V == null || drs_V.Length == 0)
                    return;

                dr_V.ItemArray = drs_V[0].ItemArray;


                RadioButton rdoPromisedDate_Old = (RadioButton)gvMain.Rows[iIndex].FindControl("PromisedDate_Old");
                if (rdoPromisedDate_Old.Checked)
                {
                    dr["EstimatedDate"] = rdoPromisedDate_Old.Text;
                }
                else
                {
                    if (dr["EstimatedDate"].ToString() == string.Empty)
                    {
                        ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "", "<script>alert('" + AlertMessage.PromisedDateNotEmpty + "')</script>", false);
                        return;
                    }
                    dr_V[BEGDC.PreContract.DAL.PreContractInfo.CONST_PromisedDate] = Convert.ToDateTime(dr["EstimatedDate"]);
                }

                RadioButton rdoCEWPromised_Old = (RadioButton)gvMain.Rows[iIndex].FindControl("CEWPromised_Old");
                if (rdoCEWPromised_Old.Checked)
                {
                    dr["Price"] = rdoCEWPromised_Old.Text;
                }
                else
                {
                    if (dr["Price"].ToString() == string.Empty)
                        dr["Price"] = 0;
                    dr_V[BEGDC.PreContract.DAL.PreContractInfo.CONST_SalePrice] = Convert.ToDecimal(dr["Price"]);
                }



                RadioButton rdoOrionNo_Old = (RadioButton)gvMain.Rows[iIndex].FindControl("OrionNo_Old");
                if (rdoOrionNo_Old.Checked)
                {
                    dr["OrionNumber"] = rdoOrionNo_Old.Text;
                }
                else
                {
                    dr_V[BEGDC.PreContract.DAL.PreContractInfo.CONST_OrionNo] = dr["OrionNumber"];
                }



                RadioButton rdoACRNo_Old = (RadioButton)gvMain.Rows[iIndex].FindControl("ACRNo_Old");
                if (rdoACRNo_Old.Checked)
                {
                    dr["EndACR"] = rdoACRNo_Old.Text;
                }
                else
                {
                    dr_V[BEGDC.PreContract.DAL.PreContractInfo.CONST_ACRNo] = dr["EndACR"];
                }


                RadioButton rdoCustomerName_Old = (RadioButton)gvMain.Rows[iIndex].FindControl("CustomerName_Old");
                if (rdoCustomerName_Old.Checked)
                {
                    dr["EndCustomer"] = rdoCustomerName_Old.Text;
                }
                else
                {
                    dr_V[BEGDC.PreContract.DAL.PreContractInfo.CONST_CustomerName] = dr["EndCustomer"];
                }
            }

            precontractServuce.UpdatePreContract_Import(ref precontractId, dr, out strMessage);

            if (strMessage != string.Empty)
            {
                ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "", strMessage, false);
                return;
            }

            if (isNew)
            {
                System.Data.DataRow[] drs_V = this.NewData.Select(string.Format("PreContractNo='{0}' And BDCode='{1}'", precontractNo, bd));
                if (drs_V == null || drs_V.Length == 0)
                    return;
                drs_V[0][BEGDC.PreContract.DAL.PreContractInfo.CONST_PreContractID] = Convert.ToInt32(precontractId);
                this.UpdatedData.Rows.Add(drs_V[0].ItemArray);

                this.NewData.Rows.Remove(drs_V[0]);
            }
            else
            {
                System.Data.DataRow[] drs_V = this.ValidateData.Select(string.Format("PreContractId='{0}'", precontractId));
                if (drs_V == null || drs_V.Length == 0)
                    return;
                this.UpdatedData.Rows.Add(dr_V.ItemArray);

                this.ValidateData.Rows.Remove(drs_V[0]);
            }

        }

    }
}
